<script setup>
import {
  ref,
  reactive,
  onMounted,
  inject,
  provide,
  computed,
  watch,
  nextTick,
  watchEffect,
} from 'vue';
import NumberPatches from '@/components/upLoad/NumberPatches.vue';
import { scrollToFormError } from '@/utils/common';
import { useRouter, useRoute } from 'vue-router';
import SmtHeader from '@/layout/SmtHeader.vue';
import SmtFooter from '@/layout/SmtFooter.vue';
import Sections from '@/components/Sections/index.vue';
import View3D from '@/components/3Dview/3Dview.vue';
import Tips from '@/components/Tips/index.vue';
import UpLoad from '@/components/upLoad/UpLoad.vue';
import { querySelectroductCraftsOrServiceFilterList } from '@/server/api/craft.js';
import { uploadDocFile, getMallFileData } from '@/server/api/file';
import useOrderStore from '@/store/modules/order';
import useAppStore from '@/store/modules/app';
import { debounce } from 'lodash';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

const orderStore = useOrderStore();
const appStore = useAppStore();

import {
  listAddress,
  gerberFilelist,
  queryCraftsCategoryList,
  getDictTypeList,
  crmPcbaOrderCalculationAmountAPI,
  getPcbaServiceCategoryList,
  getExpressCompanyList,
  addSmt,
} from '@/server/api/biz.js';
import { scrollToSection, downloadFile } from '@/utils/common.js';
import { Close } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import GroupSelectTree from '@/components/GroupSelectTree/index.vue';
// 选中的工艺服务信息
const selectedListMap = ref({});
provide('selectedListMap', selectedListMap);

const craftsRef = ref(null);

const formRef = ref();
const router = useRouter();
const route = useRoute();

const gerberFile = ref(null); // gerber文件
const ruleForm = reactive({
  orderNumber: '10', // 板子数量
  pcbLength: '', // 板子长度
  pcbWidth: '', // 板子宽度
  agreement: false, // 是否同意
  productId: null, // 板材类型id
  productName: '', // 板材类型名称
  expressDelivery: '1', // 快递方式
  craftsCategory: [], // 选中的工艺数据
  serviceCategory: [], // 选中的服务数据
  curAddressInfo: {}, // 当前选中的快递地址
  curExpressDeliveryInfo: {}, // 当前选中的快递信息
  whetherPatch: '1', // 是否贴片'
  gerberFileId: null, // Gerber文件id
  gerberFileName: '', // Gerber文件name
  renderData: [], // gerber文件列表，用于3d渲染
  layerId: '', // 板层id
});
const data = reactive({
  layerList: [], // PCB板层信息
  craftsList: [], // PCB工艺信息
  smtOptionList: [], // SMT选项列表
  productList: [], // 板材类型
  baseServieList: [], // 基础服务
  craftServideList: [], // 工艺服务
  customizedServiceList: [], // 定制服务
  disabldIdList: [], // 禁用选项ID列表
});

// 智能报价账单信息
const billInfo = ref({});
const viewRef = ref();

const rules = reactive({
  orderNumber: [
    {
      required: true,
      message: t('mall.enter_board_quantity'),
      trigger: 'change',
    },
  ],
  productId: [
    {
      type: 'array',
      required: true,
      message: t('mall.choose_material_type'),
      trigger: 'change',
    },
  ],
  desc: [{ required: true, message: 'Please input activity form', trigger: 'blur' }],
  layerId: [
    {
      required: true,
      message: t('mall.choose_board_layer'),
      trigger: 'change',
    },
  ],
});

onMounted(() => {
  initData();
});

// 初始化数据
const initData = () => {
  getFiledList();
  getCachedDetail();
  getHomeQueryData();
  getSmtToPcbShowWhetherPatch();
  getProductList();
};

const getSmtToPcbShowWhetherPatch = () => {
  const { whetherPatch } = route.query;
  ruleForm.whetherPatch = whetherPatch || '1';
};

// 首页回显数据
const getHomeQueryData = () => {
  const { productId, pcbLength, pcbWidth, orderNumber } = route.query;
  if (productId) {
    ruleForm.productId = productId;
  }
  if (pcbLength) {
    ruleForm.pcbLength = pcbLength;
  }
  if (pcbWidth) {
    ruleForm.pcbWidth = pcbWidth;
  }
  if (orderNumber) {
    ruleForm.orderNumber = orderNumber;
  }
};
// 首页回显板层数据
const getHomeLayerData = () => {
  // 回显板层信息
  const boardLayer = route.query.boardLayer;
  if (boardLayer && data.layerList.length > 0) {
    // 获取板层信息
    const layerOptionList = data.layerList[0].children;
    const layerInfo = layerOptionList.find((item) => item.craftsName === boardLayer);
    ruleForm.layerId = layerInfo.id;
  }
};

// 默认回显数据
const getCachedDetail = () => {
  // 选中的服务工艺信息
  const pcbSelectedInfo = orderStore.pcbSelectedListMap;
  console.log(pcbSelectedInfo, 'selectedListMap.value');

  if (Object.keys(pcbSelectedInfo).length) {
    selectedListMap.value = pcbSelectedInfo;
    if (craftsRef.value) {
      craftsRef.value.forEach((ref) => {
        ref.initCachedData();
      });
    }
  }
  // 选中的pcb订单信息
  const pcbOrderInfo = orderStore.pcbOrderInfo;
  if (Object.keys(pcbOrderInfo).length > 0) {
    ruleForm.layerId = pcbOrderInfo.layerId; // 板层
    ruleForm.orderNumber = pcbOrderInfo.orderNumber; // 板子数量
    ruleForm.pcbLength = pcbOrderInfo.pcbLength; // 板子长度
    ruleForm.pcbWidth = pcbOrderInfo.pcbWidth; // 板子宽度
    ruleForm.agreement = pcbOrderInfo.agreement; // 是否同意
    ruleForm.productId = pcbOrderInfo.productId; // 板材类型id
    ruleForm.productName = pcbOrderInfo.productName; // 板材类型名称
    ruleForm.craftsCategory = pcbOrderInfo.craftsCategory; // 选中的工艺数据
    ruleForm.serviceCategory = pcbOrderInfo.serviceCategory; // 选中的服务数据
    ruleForm.whetherPatch = pcbOrderInfo.whetherPatch; // 是否贴片
    ruleForm.gerberFileId = pcbOrderInfo.gerberFileId; // Gerber文件id
    ruleForm.gerberFileName = pcbOrderInfo.gerberFileName; // Gerber文件name
    ruleForm.renderData = pcbOrderInfo.renderData;
    getGerberFilelist(ruleForm.gerberFileId);
    // 重新报价
    getPcbQuote();
  }
};
// 计价描述
const pricingDesc = computed(() => {
  const info = [];
  if (ruleForm.pcbLength && ruleForm.pcbWidth) {
    info.push(`${ruleForm.pcbLength}X${ruleForm.pcbWidth}cm`);
  }
  if (data.layerList.length > 0) {
    // 获取板层信息
    const layerOptionList = data.layerList[0].children;
    const layerInfo = layerOptionList.find((item) => item.id === ruleForm.layerId);
    if (layerInfo) {
      info.push(`${t('mall.layer_board', { num: layerInfo.craftsName })}`);
    }
  }
  // 板子数量
  if (ruleForm.orderNumber) {
    info.push(`${t('mall.sets', { num: ruleForm.orderNumber })}`);
  }
  return info.join(',');
});

// 工艺服务必填校验规则
const formItemRule = (item, label) => {
  return [
    {
      required: item.requiredSelect === 1,
      message: `${t('mall.please_select')}${item[label]}`,
      trigger: 'blur',
    },
  ];
};

// 获取产品名称
watch(
  () => ruleForm.productId,
  (productId) => {
    ruleForm.productName = data.productList.find((item) => item.categoryId === productId)?.name;
  },
);

// 板层变化
watch(
  () => ruleForm.layerId,
  () => {
    // ruleForm.craftsCategory = []
    // ruleForm.serviceCategory = []
    // selectedListMap.value = []
    if (ruleForm.productId) {
      getDisabledOptionList();
    }
    setSelectedLayerList();
    if (craftsRef.value) {
      craftsRef.value.forEach((ref) => {
        ref.clearSelectedValue();
        ref.initDefaultData();
        getPcbQuote();
      });
    }

    // 显示默认板层
    // if (data.layerList.length > 0) {
    //   const [{ id: layerId }] = data.layerList[0].children.filter(
    //     (item) => item.defaultSelect === 1,
    //   );
    //   console.log('----->id', layerId);
    //   ruleForm.layerId = layerId;
    // }
  },
);

// 产品变化
watch(
  () => ruleForm.productId,
  () => {
    // ruleForm.craftsCategory = []
    // ruleForm.serviceCategory = []
    // selectedListMap.value = []
    if (ruleForm.productId) {
      getDisabledOptionList();
    }
    setSelectedLayerList();
    if (craftsRef.value) {
      craftsRef.value.forEach((ref) => {
        ref.clearSelectedValue();
        ref.initDefaultData();
        getPcbQuote();
      });
      // 选中默认板层
      if (data.layerList.length) {
        const [{ id: layerId }] = data.layerList[0].children.filter(
          (item) => item.defaultSelect === 1,
        );
        ruleForm.layerId = layerId;
      }
    }
  },
);

watch(
  () => ruleForm.pcbWidth,
  () => getPcbQuote(),
);
watch(
  () => ruleForm.pcbLength,
  () => getPcbQuote(),
);

/**
 * 获取表单字段
 * @param {*} row
 */
const getFiledList = () => {
  getPcbLayerList();
  getPcbCraftsCategoryList();
  getServiceListGroup();
  getSmtOptionList();
};

/**
 * 获取产品分类列表
 */
const getProductList = () => {
  getDictTypeList({
    businessType: 1,
  }).then((res) => {
    if (res.code === 200) {
      data.productList = res.data;
      // 产品id为空，默认选第一个
      if (!ruleForm.productId && data.productList.length > 0) {
        ruleForm.productId = data.productList[0].categoryId;
      }
    } else {
      ElMessage.error(res.msg);
    }
  });
};

/**
 * 获取PCB工艺分类列表
 */
const getPcbCraftsCategoryList = async () => {
  const res = await queryCraftsCategoryList({
    businessType: 1,
    mainCategory: 2, // 是否为板层1是，2否
  });
  if (res.code === 200) {
    data.craftsList = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

/**
 * 获取PCB板层选项列表
 */
const getPcbLayerList = async () => {
  const res = await queryCraftsCategoryList({
    businessType: 1,
    mainCategory: 1, // 是否为板层1是，2否
  });
  if (res.code === 200) {
    data.layerList = res.data;
    // 获取默认板层
    const pcbOrderInfo = orderStore.pcbOrderInfo;
    if (Object.keys(pcbOrderInfo).length > 0) {
      ruleForm.layerId = pcbOrderInfo.layerId; // 缓存的板层数据
    } else {
      // 选中默认板层
      const [{ id: layerId }] = data.layerList[0].children.filter(
        (item) => item.defaultSelect === 1,
      );
      ruleForm.layerId = layerId;
      getHomeLayerData();
    }
  } else {
    ElMessage.error(res.msg);
  }
};

/**
 * 获取定制服务列表组
 */
const getServiceListGroup = async () => {
  const res = await getPcbaServiceCategoryList({
    businessType: 1,
  });
  if (res.code === 200) {
    // 1 基础服务 2 定制服务 3 工艺服务
    data.baseServieList = res.data['1'] || [];
    data.customizedServiceList = res.data['2'] || [];
    data.craftServideList = res.data['3'] || [];
  } else {
    ElMessage.error(res.msg);
  }
};

/**
 * 获取SMT选项列表
 */
const getSmtOptionList = async () => {
  const res = await queryCraftsCategoryList({
    businessType: 1, // smt是2
  });
  if (res.code === 200) {
    data.smtOptionList = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

/**
 * 确认上传贴片数量
 */
const getPcbQuote = () => {
  const { pcbLength, pcbWidth, orderNumber } = ruleForm;
  if (pcbLength && pcbWidth && orderNumber) {
    const params = {
      pcbLength, // 板子长度
      pcbWidth, // 板子宽度
      layer: 1, // pcb 默认为1
      smtNumber: orderNumber,
      business: 1, // 业务产品 1pcb,2pcba,3组包装工艺
    };
    if (ruleForm.craftsCategory.length > 0) {
      // 选中的工艺信息
      params.craftsCategory = ruleForm.craftsCategory;
    }
    if (ruleForm.serviceCategory.length > 0) {
      // 选中的服务信息
      params.serviceCategory = ruleForm.serviceCategory;
    }
    crmPcbaOrderCalculationAmountAPI(params).then((res) => {
      if (res.code == 200) {
        billInfo.value = res.data;
      } else {
        ElMessage.error(res.msg);
      }
    });
  }
};

/**
 * 订单提交
 * @param {*} formEl
 */
const submitForm = async (formEl) => {
  if (!ruleForm.productId) {
    return ElMessage.warning(t('mall.choose_material_type'));
  }

  if (!ruleForm.gerberFileId) {
    return ElMessage.warning(t('mall.upload_gerber_first'));
  }

  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (!ruleForm.agreement) {
        return ElMessage.warning(t('mall.agree_terms_checkbox'));
      }
      if (ruleForm.productId) {
        ruleForm.productName = data.productList.find(
          (item) => item.categoryId === ruleForm.productId,
        )?.name;
      }
      setSelectedLayerList();
      orderStore.setPcbOrderInfo({ ...ruleForm, billInfo: billInfo.value });
      // 是否需要贴片 1不需要
      if (ruleForm.whetherPatch == '1') {
        router.push({
          path: '/settlement',
        });
      } else {
        router.push({
          path: '/pricing/smt',
          query: {
            orderNumber: ruleForm.orderNumber,
          },
        });
      }
      console.log('submit!');
    } else {
      nextTick(() => {
        //加个定时器，有可能监测不到页面变化
        let timer = setTimeout(function () {
          scrollToFormError();
          clearTimeout(timer);
        }, 200);
      });
      for (let key in fields) {
        const errorMessage = fields[key][0].message;
        ElMessage.error(errorMessage);
        return false;
      }
    }
  });
};

/**
 * 获取尺寸
 * @param {*} data
 */
const getDimensions = (item) => {
  ruleForm.pcbLength = item.h.toFixed(2);
  ruleForm.pcbWidth = item.w.toFixed(2);
};

/**
 * gerber上传
 * @param {*} file
 */
const userUploadFilePath = ref();

const gerberUpload = (file) => {
  const { orderNumber: quantity } = ruleForm;
  uploadDocFile({
    fileType: 1,
    quantity,
    isUseAlternative: 1,
    smtLayer: 1,
    batchYearLimit: 0,
    file,
  }).then((res) => {
    if (res.code === 200) {
      ElMessage.success(t('mall.upload_successful'));
      ruleForm.gerberFileId = res.data.fileId;
      ruleForm.gerberFileName = res.data.name;
      userUploadFilePath.value = res.data.path;
      getGerberFilelist(res.data.fileId);
    } else {
      ElMessage.error(res.msg);
    }
  });

  // if (quantity) {
  //   uploadDocFile({
  //     fileType: 1,
  //     quantity,
  //     isUseAlternative: 1,
  //     smtLayer: 1,
  //     batchYearLimit: 0,
  //     file,
  //   }).then((res) => {
  //     if (res.code === 200) {
  //       ElMessage.success(t('mall.upload_successful'));
  //       ruleForm.gerberFileId = res.data.fileId;
  //       ruleForm.gerberFileName = res.data.name;
  //       getGerberFilelist(res.data.fileId);
  //     } else {
  //       ElMessage.error(res.msg);
  //     }
  //   });
  // } else {
  //   scrollToSection('#basicInfor');
  // }
};

/**
 * 获取gerber文件列表
 * @param {*} id
 */
const getGerberFilelist = (id) => {
  gerberFilelist(id).then((res) => {
    if (res.code === 200) {
      getGerberFileData(res.data);
    } else {
      ElMessage.error(res.msg);
    }
  });
};

/**
 * 获取gerber文件数据
 * @param {*} data
 */
const getGerberFileData = (data) => {
  const requestsList = data.map((item) => {
    return getMallFileData(item.gerberFilePath);
  });
  Promise.all(requestsList).then((res) => {
    ruleForm.renderData = res;
    viewRef.value.readFiles(res, data);
  });
};

// const handleInput = (value) => {
//   // 用正则表达式限制输入最多两位小数
//   const regex = /^\d*(\.\d{0,2})?$/;
//   if (regex.test(value)) {
//     this.inputValue = value;
//   } else {
//     // 如果输入不符合规则，则回退到上一个有效值
//     this.inputValue = this.inputValue.toString().match(/^\d*(\.\d{0,2})?/)[0];
//   }
// };

/**
 * 获取上传文件file
 * @param {*} file
 */
const getFlieData = (file) => {
  gerberFile.value = file;
  gerberUpload(file);
};

// 首页过来获取板子类型
const { productId, boardLayer, pcbLength, pcbWidth, orderNumber } = route.query;
const getLayerData = () => {
  if (productId || boardLayer || pcbLength || pcbWidth || orderNumber) {
    // 商品类型
    ruleForm.productId = productId;
    ruleForm.pcbLength = pcbLength;
    ruleForm.pcbWidth = pcbWidth;
    ruleForm.orderNumber = orderNumber;
  }
};

getLayerData();

// 选中工艺服务
const onChangeSelectedData = (groupData, currentSelectedList) => {
  // 切换工艺
  if (currentSelectedList.filter((item) => item.mainCategory === 1).length > 0) {
    getDisabledOptionList(currentSelectedList);
  }
  // 构造表单校验数据
  Object.keys(groupData).forEach((key) => {
    const valueList = groupData[key].map((item) => item.id);
    const [value] = valueList; // 单选为字符串， 多选为数组集合
    ruleForm[key] = valueList.length === 1 ? value : valueList;
    // 数据变化时，重新触发该字段的校验
    formRef.value.validateField([key]);
  });
  orderStore.setPcbSelectedListMap(groupData);
  getSelectedData(groupData);
  // 请求右侧的PCB报价,获取信息
  const { pcbLength, pcbWidth, orderNumber } = ruleForm;
  if (pcbLength && pcbWidth && orderNumber) {
    getPcbQuote();
  } else {
    // ElMessage.warning('请先填写板子尺寸、板子数量');
  }
};

// 处理子组件工艺选中的数据
const getSelectedData = (groupData) => {
  const slectedGroupList = Object.values(groupData);
  const selectedList = slectedGroupList.flat().map((item) => ({
    ...item,
    orderNumber: ruleForm.orderNumber,
  }));
  const selectedServiceList = selectedList.filter((item) => 'serviceKey' in item);
  const selectedCraftList = selectedList.filter((item) => 'craftsKey' in item);
  ruleForm.craftsCategory = selectedCraftList;
  ruleForm.serviceCategory = selectedServiceList;
  setSelectedLayerList();
};

// 获取禁用选项列表
const getDisabledOptionList = () => {
  querySelectroductCraftsOrServiceFilterList({
    business: 1,
    productId: ruleForm.productId,
    mainId: ruleForm.layerId,
  }).then((res) => {
    if (res.code === 200 && Array.isArray(res.data) && res.data.length > 0) {
      data.disabldIdList = res.data.map((item) => item.relationId);
    }
  });
};

// 获取选中的板层项
const setSelectedLayerList = () => {
  if (data.layerList.length > 0) {
    // 获取板层信息
    const layerOptionList = data.layerList[0].children;
    const selectedLayerInfo = layerOptionList.find((item) => item.id === ruleForm.layerId);
    const layerIndex = ruleForm.craftsCategory.findIndex(
      (item) => item.parentId === data.layerList[0].id,
    );
    // 判断是否有板层存在
    if (layerIndex > -1) {
      ruleForm.craftsCategory.splice(layerIndex, 1, selectedLayerInfo);
    } else {
      ruleForm.craftsCategory.push(selectedLayerInfo);
    }
  }
};

// 检验gerber是否上传
const checkGerberFileIsExist = () => {
  debouncedMethod();
};

const debouncedMethod = debounce(() => {
  getPcbQuote();
}, 500); // 设置延迟时间，单位为毫秒

const widthHeightChange = () => {
  debouncedMethod();
};

// 下载pcb文件
const downloadPcbFile = () => {
  downloadFile(userUploadFilePath.value);
};

// 板层变化
const onChangeLayerId = () => {};

// 用户协议链接
const agreementUrl = computed(() => {
  const lang = appStore.language;
  switch (lang) {
    case 'en':
      return window.location.origin + '/#/user-agreement/en_US';
    default:
      return window.location.origin + '/#/user-agreement';
  }
});

// 语言切换
const onChangeLang = () => {
  initData();
};

// 免责申明跳转
const handleNavToAgreement = () => {
  const lang = appStore.language;
  const protocol = window.location.protocol;
  const host = window.location.host;
  const currentPath = protocol + '//' + host;
  window.location.href = currentPath;
  window.open('http://localhost:5173/#/user-agreement/en_US');
  switch (lang) {
    case 'en':
      // console.log(`${currentPath}/#/user-agreement/en_US`);
      break;
    default:
      // window.open(`${currentPath}#/user-agreement `, '_blank');
      // window.open(`http://localhost:5173/#/user-agreement/en_US`, '_blank');
      break;
    // router.push({
    //   path: '/user-agreement',
    // });
  }
};
</script>

<template>
  <div class="wrapper">
    <!-- 头部 -->
    <smt-header @lang-change="onChangeLang"></smt-header>
    <div class="pricing-pcb container">
      <!-- 主内容 -->
      <div class="pricing-pcb-main">
        <el-breadcrumb :separator-icon="ArrowRight" class="f-28" style="padding-bottom: 20px">
          <el-breadcrumb-item>{{ $t('menu.home') }}</el-breadcrumb-item>
          <el-breadcrumb-item>{{ $t('mall.quote') }}</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- <div class="title">
          <img :src="images['line-CPU@2x']" alt="" />
          <span>PCB 在线下单</span>
        </div> -->
        <!--  上传文件容器 -->
        <UpLoad
          :name="
            ruleForm.gerberFileId ? $t('mall.reupload_gerber_file') : $t('pcb.UploadGerberfiles')
          "
          fileType="1"
          :smdNum="ruleForm.orderNumber"
          :warningTitle="$t('om.ofboards')"
          @getFlieData="getFlieData"
          @scrollToSection="scrollToSection"
        >
          <p class="pcb-file-name" @click="downloadPcbFile">{{ ruleForm.gerberFileName }}</p>
          <p class="upload-tip" style="color: red">
            {{ $t('pcb.PCBfileformatmust') }}
          </p>
        </UpLoad>
        <el-form
          ref="formRef"
          :model="ruleForm"
          :rules="rules"
          hide-required-asterisk
          label-position="left"
          label-width="160px"
        >
          <!-- 基本信息 -->
          <Sections :title="$t('pcb.BasicInfo')" style="margin-bottom: 20px">
            <el-form-item :label="$t('pcb.PlateType')" prop="type" style="align-items: center">
              <template #label>
                <span style="padding-right: 5px; color: red">*</span>
                {{ $t('pcb.PlateType') }}<Tips :content="$t('pcb.MaterialType')" />
              </template>
              <el-radio-group class="offset-margin" v-model="ruleForm.productId">
                <el-radio
                  class="pcb-radio"
                  :label="item.categoryId"
                  border
                  v-for="item in data.productList"
                  :key="item.categoryId"
                >
                  <el-popover placement="top" :width="200" trigger="hover">
                    <template #reference>
                      <div class="pcb-radio-item">
                        <img src="@/assets/images/icons/icon_fr_4.svg" alt="" />
                        <p>{{ item.name }}</p>
                      </div>
                    </template>
                    <div class="h-70" style="display: flex; justify-content: center">
                      <img class="h-120" src="@/assets/images/icons/icon_fr_4.png" alt="" />
                    </div>
                  </el-popover>
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item :label="$t('pcb.BoardSize')">
              <template #label>
                <span style="padding-right: 5px; color: red">*</span>
                {{ $t('pcb.BoardSize') }}
                <Tips :content="$t('pcb.BoardSizeDesc')" />
              </template>
              <!-- <el-form-item
                prop="pcbLength"
                :rules="{
                  required: true,
                  message: '请输入长度',
                  trigger: 'change',
                }"
              > -->
              <el-input
                class="size-input"
                v-model="ruleForm.pcbLength"
                v-number="2"
                :placeholder="`${$t('mall.length')}`"
                style="width: 80px"
                @change="widthHeightChange"
              />
              <!-- </el-form-item> -->

              <span class="m-5"
                ><el-icon style="margin-top: -15px"><Close /> </el-icon>
              </span>
              <!-- <el-form-item
                prop="pcbWidth"
                :rules="{
                  required: true,
                  message: '请输入宽度',
                  trigger: 'change',
                }"
              > -->
              <el-input
                class="size-input"
                v-model="ruleForm.pcbWidth"
                v-number="2"
                :placeholder="`${$t('mall.width')}`"
                style="width: 80px"
                @change="widthHeightChange"
              />
              <!-- </el-form-item> -->

              <span class="m-5">cm</span>
            </el-form-item>

            <el-form-item :label="$t('pcb.ofboards')" prop="orderNumber" id="basicInfor">
              <template #label>
                <span style="padding-right: 5px; color: red">*</span>
                {{ $t('pcb.ofboards') }}<Tips :content="$t('pcb.BoardQuantityDesc')" />
              </template>
              <el-input
                v-model="ruleForm.orderNumber"
                v-number
                :placeholder="$t('pcb.ofboards')"
                style="width: 182px"
                :maxlength="8"
                @input="checkGerberFileIsExist"
              />
            </el-form-item>
          </Sections>

          <!-- PCB工艺信息 -->
          <Sections :title="$t('pcb.PCBProcessInformation')" v-if="data.craftsList.length > 0">
            <!-- 板层工艺 -->
            <el-form-item
              :rules="rules"
              v-for="item in data.layerList"
              :key="item.id"
              prop="layerId"
              class="basic-service board-crafts"
            >
              <template #label>
                <span v-if="item.requiredSelect === 1" style="padding-right: 5px; color: red"
                  >*</span
                >
                {{ item.craftsName }}
                <Tips :title="item.serviceName" :content="item.remark" />
              </template>
              <el-radio-group
                class="offset-margin"
                v-model="ruleForm.layerId"
                @change="onChangeLayerId"
              >
                <div v-for="(child, i) in item.children" :key="i" style="margin: 0 20px 8px 0">
                  <el-radio class="layer-radio" border :label="child.id">
                    {{ child.craftsName }}
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
            <!-- PCB工艺信息 -->
            <el-form-item
              :rules="formItemRule(item, 'craftsName')"
              v-for="item in data.craftsList"
              :key="item.id"
              :prop="item.id"
              class="basic-service"
            >
              <template #label>
                <span v-if="item.requiredSelect === 1" style="padding-right: 5px; color: red"
                  >*</span
                >
                {{ item.craftsName }}
                <Tips :title="item.serviceName" :content="item.remark" />
              </template>
              <group-select-tree
                ref="craftsRef"
                :parentData="item"
                :tree-data="item.children"
                :disabldIdList="data.disabldIdList"
                @selected="onChangeSelectedData"
              />
            </el-form-item>
          </Sections>

          <!-- 基础服务 -->
          <Sections :title="$t('smt.Basicservices')" v-if="data.baseServieList.length">
            <el-form-item
              :rules="formItemRule(item, 'serviceName')"
              v-for="item in data.baseServieList"
              :key="item.id"
              :prop="item.id"
              class="basic-service"
            >
              <template #label>
                <span v-if="item.requiredSelect === 1" style="padding-right: 5px; color: red"
                  >*</span
                >
                {{ item.serviceName }}
                <Tips :title="item.serviceName" :content="item.remark" />
              </template>
              <group-select-tree
                ref="craftsRef"
                :parentData="item"
                :tree-data="item.children"
                :disabldIdList="data.disabldIdList"
                :props="{ optionName: 'serviceName' }"
                @selected="onChangeSelectedData"
              />
            </el-form-item>
          </Sections>

          <!-- 工艺服务 -->
          <Sections :title="$t('mall.process_service')" v-if="data.craftServideList.length">
            <el-form-item
              :rules="formItemRule(item, 'serviceName')"
              v-for="item in data.craftServideList"
              :key="item.id"
              :prop="item.id"
              class="basic-service"
            >
              <template #label>
                <span v-if="item.requiredSelect === 1" style="padding-right: 5px; color: red"
                  >*</span
                >
                {{ item.serviceName }}
                <Tips :title="item.serviceName" :content="item.remark" />
              </template>
              <group-select-tree
                ref="craftsRef"
                :tree-data="item.children"
                :parentData="item"
                :props="{ optionName: 'serviceName' }"
                :disabldIdList="data.disabldIdList"
                @selected="onChangeSelectedData"
              />
            </el-form-item>
          </Sections>

          <!-- 定制服务 -->
          <Sections :title="$t('smt.Customizedservices')" v-if="data.customizedServiceList.length">
            <el-form-item
              v-for="item in data.customizedServiceList"
              :rules="formItemRule(item, 'serviceName')"
              :key="item.id"
              :prop="item.id"
              class="basic-service"
            >
              <template #label>
                <span v-if="item.requiredSelect === 1" style="padding-right: 5px; color: red"
                  >*</span
                >
                {{ item.serviceName }}
                <Tips :title="item.serviceName" :content="item.remark" />
              </template>
              <group-select-tree
                ref="craftsRef"
                :parentData="item"
                :tree-data="item.children"
                :props="{ optionName: 'serviceName' }"
                :disabldIdList="data.disabldIdList"
                @selected="onChangeSelectedData"
              />
            </el-form-item>
          </Sections>
          <!-- SMT选项 -->
          <Sections :title="$t('pcb.SMTOptions')">
            <el-form-item prop="whetherPatch" class="basic-service">
              <template #label>
                <span style="padding-right: 5px; color: red">*</span>
                {{ $t('pcb.SMTornot') }}
              </template>
              <el-radio-group class="offset-margin" v-model="ruleForm.whetherPatch">
                <el-radio label="1" border>{{ $t('pcb.Noneed') }}</el-radio>
                <el-radio label="2" border>{{ $t('pcb.Takeup') }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </Sections>
          <!-- 快递方式 -->
          <!-- <Sections :title="$t('smt.Expressway')">
            <div class="block-wrap" id="expressDelivery">
              <el-form-item prop="expressDelivery">
                <template #label> {{ $t('smt.Expressway') }}<Tips content="1" /> </template>
                <el-row class="row-item">
                  <el-radio-group v-model="ruleForm.expressDelivery">
                    <el-radio
                      v-for="(item, index) in data.expressDeliveryList"
                      :key="index"
                      :label="item.id"
                      @change="handleExpressDeliveryChange(item)"
                      >{{ item.name }}</el-radio
                    >
                  </el-radio-group>
                </el-row>
              </el-form-item>
            </div>
          </Sections> -->
          <!-- <Sections :title="$t('smt.Shippingaddress')">
            <div class="block-wrap">
              <div class="title-wrap">
                <div class="flex">
                  <el-form-item prop="address">
                    <template #label>
                      {{ $t('smt.Selectshippingaddress') }}<Tips content="1" />
                    </template>
                    <div class="text">
                      <span>{{ expressAddress }}</span>
                    </div>
                  </el-form-item>
                </div>
                <div class="edit-btn" @click="handleEditAddress()">
                  <img
                    class="edit-icon"
                    src="@/assets/images/icons/icon_edit.svg"
                    width="18"
                    height="18"
                  />
                  <span>选择</span>
                </div>
              </div>
            </div>
          </Sections> -->
          <!-- 收货地址弹窗 -->
          <!-- <SelectAddressDialog
            v-model="data.addressVisible"
            :title="data.title"
            :addressList="data.addressList"
            @getAddressList="getAddressList"
            @cancel="cancelAddr"
            @selected="handleSelectedAddress"
          /> -->
        </el-form>
      </div>

      <!-- 右侧记价容器 -->
      <div class="side-content">
        <div class="gerber-viewer-wrap">
          <View3D
            ref="viewRef"
            v-show="ruleForm.renderData.length > 0"
            @getDimensions="getDimensions"
          />
        </div>
        <!-- 智能报价信息 -->
        <div class="summary-box">
          <div class="summary-box-title-wrap">
            <img src="@/assets/images/icons/icon-bill@2x.png" />
            <h2 class="summary-box-title">{{ $t('smt.SmartQuote') }}</h2>
          </div>
          <div class="summary-box-content">
            <!-- 计价项 -->
            <div class="summary-box-content-item">
              <div class="content-item-left">
                <p class="label">{{ $t('smt.PCBBilling') }}</p>
                <p v-if="pricingDesc" class="desc">{{ pricingDesc }}</p>
                <p v-else class="desc">{{ $t('pcb.Notavailable') }}</p>
              </div>
              <div class="content-item-right">
                <p class="price">{{ billInfo.symbol }}{{ billInfo.craftsServiceAmount || 0 }}</p>
              </div>
            </div>
            <!-- 计价项 -->
            <div class="summary-box-content-item">
              <div class="content-item-left">
                <p class="label">{{ $t('pcb.Courierfee') }}</p>
                <p class="desc">{{ deliveryCompany }}</p>
              </div>
              <div class="content-item-right">
                <p class="price rigth-title">{{ $t('mall.based_on_actual_costs') }}</p>
              </div>
            </div>
            <!-- 计价项 -->
            <div class="summary-box-content-item">
              <div class="content-item-left">
                <p class="label">{{ $t('pcb.Taxes') }}</p>
                <!-- <p class="desc">{{ $t('pcb.Valueadded') }} {{ billInfo.tax || 0 }}%</p> -->
              </div>
              <div class="content-item-right">
                <p class="price rigth-title">{{ $t('mall.based_on_actual_costs') }}</p>
              </div>
            </div>
            <!-- 总计 -->
            <div class="summary-box-content-item summary-item">
              <div class="content-item-left">
                <p class="label" style="font-weight: bold">{{ $t('mall.estimated_cost') }}</p>
              </div>
              <div class="content-item-right">
                <p class="total-price">
                  {{ billInfo.symbol }}{{ billInfo.payCurrencyTaxAmount || 0 }}
                </p>
              </div>
            </div>
            <div class="end-price">{{ $t('mall.final_cost_subject_to_review') }}</div>
            <div class="button-wrap">
              <el-button class="submit-btn" type="primary" @click="submitForm(formRef)">{{
                $t('mall.next_step')
              }}</el-button>
              <div class="user-agreement">
                <div class="user-agreement">
                  <el-checkbox label="1" size="large" v-model="ruleForm.agreement"
                    ><div style="display: flex; align-items: center">
                      <span>{{ $t('mall.read_disclaimer') }}</span>
                      <el-link type="primary" :href="agreementUrl" target="_blank"
                        >《{{ $t('mall.disclaimer') }}》</el-link
                      >
                    </div>
                  </el-checkbox>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部 -->
    <smt-footer></smt-footer>
  </div>
</template>
<style lang="scss" scoped>
.pricing-pcb-main {
  padding: 20px;
}

.pcb-file-name {
  cursor: pointer;
  color: #5255fe;
}

.f-20 {
  font-size: 20px;
}
.title {
  display: flex;
  align-items: center;
  padding: 20px 0;
  font-size: 18px;
  font-weight: 700;
  color: var(--mall-text-color-primary);
  img {
    width: 24px;
    height: 24px;
    margin-right: 12px;
  }
}
.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.text {
  color: #a6a6a6;
  font-size: 14px;
}
.block-title {
  width: 121px;
  color: var(--mall-text-color-primary);
  font-size: 18px;
  font-weight: 500;
}
.block-wrap {
  padding: 0 24px;
  border-bottom: 1px solid #f5f5f5;
  &:last-child {
    border: none;
  }

  .title-wrap {
    display: flex;
    justify-content: space-between;
    &.table-title {
      padding-top: 24px;
      padding-bottom: 12px;
    }
    .block-title {
      width: 121px;
      color: var(--mall-text-color-primary);
      font-size: 18px;
      font-weight: 500;
    }
    .edit-btn {
      display: flex;
      align-items: center;
      cursor: pointer;
      padding-left: 16px;
      font-size: 14px;
      color: #5255fe;
      > img {
        vertical-align: middle;
        width: 18px;
      }
      > a {
        display: inline-block;
        padding-left: 14px;
        color: var(--mall-color-primary);
        font-family: 'SourceHanSansCN';
      }
    }
  }

  .row-item {
    padding-top: 12px;
    color: var(--mall-text-color-primary);
    font-size: 14px;
    display: table-caption;
    .pay-icons-wrap {
      padding-left: 142px;
      .pay-icon {
        height: 24px;
        margin-bottom: 24px;
      }
      .pay-row {
        > img {
          height: 32px;
          margin-right: 12px;
        }
      }
    }
  }
}
.h-70 {
  height: 70px;
}
.h-120 {
  height: 100%;
  object-fit: cover;
}
.m-5 {
  margin-left: 5px;
  margin-right: 5px;
}
.wrapper {
  background: var(--mall-body-bg-color);
}
.pricing-pcb {
  display: flex;
  padding-top: 12px;
  padding-bottom: 72px;

  &.container {
    padding: 20px 240px;
    margin: 0 auto;
  }
  &-main {
    box-sizing: border-box;
    padding: 20px;
    flex: 1;
    width: 1040px;
    margin-right: 20px;
    background: #fff;
    box-sizing: border-box;
    border-radius: 8px;

    .upload-box {
      padding: 24px;
      // padding-top: 36px;
      margin-bottom: 24px;
      border-radius: 8px;
      background: #f5f5f5;
      height: 140px;
      .upload-tip {
        padding-top: 6px;
        text-align: center;
        color: #a6a6a6;
        font-size: 14px;
      }
    }

    .offset-margin {
      // 抵消radio-item底边边距
      margin-bottom: -14px;
    }

    .pcb-radio {
      height: 60px;
      .pcb-radio-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        > img {
          padding-top: 8px;
          width: 60px;
        }
      }
    }
    .color-radio {
      > i {
        &.white {
          border: 1px solid var(--mall-text-color-primary);
        }
        display: inline-block;
        vertical-align: middle;
        width: 16px;
        height: 16px;
        margin-right: 12px;
        border-radius: 50%;
      }
    }
  }

  .side-content {
    position: sticky;
    top: 90px;
    .gerber-viewer-wrap {
      // position: sticky;
      // top: 90px;
    }
    .summary-box {
      position: sticky;
      top: 90px;
      width: 302px;
      border-radius: 10px;
      background: #ffffff;
      &-title-wrap {
        padding: 0 22px;
        display: flex;
        align-items: center;
        border-bottom: 1px solid #e5e5e5;
        > img {
          width: 15px;
          height: 17px;
          margin-right: 12px;
        }
      }
      &-title {
        height: 60px;
        display: flex;
        align-items: center;
        color: var(--mall-text-color-primary);
        font-size: 14px;
        font-weight: 400px;
      }
      &-content {
        &-item {
          display: flex;
          padding: 12px;
          border-bottom: 1px solid #e5e5e5;
          // justify-content: space-between;
          .content-item-left {
            width: 180px;
            .label {
              color: #383838;
              font-weight: 400;
              color: var(--mall-text-color-primary);
              font-size: 14px;
              font-family: 'SourceHanSansCN';
              padding-bottom: 10px;
            }
            .desc {
              padding-top: 5px;
              color: #808080;
              font-size: 12px;
            }
          }
          .content-item-right {
            color: #ff0000;
            .total-price {
              font-size: 18px;
              font-weight: 700;
            }
            .total-time {
              padding-top: 16px;
              color: #888888;
              font-size: 12px;
            }
            .rigth-title {
              color: #888888;
              font-size: 12px;
            }
          }
        }

        .summary-item {
          border-bottom: 0;
          height: auto;
        }

        .end-price {
          margin-top: -10px;
          margin-bottom: 10px;
          margin-left: 14px;
          font-size: 13px;
          color: red;
        }
        .button-wrap {
          padding: 4px 12px 12px;
          .submit-btn {
            width: 100% !important;
          }
          ::v-deep .el-button--primary {
            height: 32px !important;
            font-weight: 400;
          }
          .user-agreement {
            display: flex;
            a {
              display: inline-block;
            }
          }
        }
      }
    }
  }
}

::v-deep .el-upload-dragger {
  background: transparent;
  padding: 0;
  border: 0;
}

::v-deep .el-form {
  .el-form-item {
    margin-bottom: 24px;
    .el-form-item__label {
      font-size: 16px;
      line-height: 20px;
      display: flex;
      align-items: center;
    }
  }
}

::v-deep .el-radio-group {
  max-width: 612px;
}

::v-deep .el-form-item {
  margin-bottom: 14px !important;
}

.basic-service ::v-deep .el-form-item__error {
  margin-top: -8px;
}

.board-crafts {
  margin-bottom: 14px !important;
}
</style>
